from django.db import models
from django.contrib.auth import get_user_model
from apps.flowers.models import Flower, FlowerSpec

User = get_user_model()


class Order(models.Model):
    """订单模型"""
    STATUS_CHOICES = [
        ('pending', '待付款'),
        ('paid', '已付款'),
        ('processing', '处理中'),
        ('shipped', '已发货'),
        ('delivered', '已送达'),
        ('completed', '已完成'),
        ('cancelled', '已取消'),
        ('refunded', '已退款'),
    ]

    order_no = models.CharField(max_length=32, unique=True, verbose_name="订单号")
    user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name="用户")
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='pending', verbose_name="订单状态")
    
    # 收货信息
    receiver_name = models.CharField(max_length=50, verbose_name="收货人姓名")
    receiver_phone = models.CharField(max_length=11, verbose_name="收货人电话")
    receiver_address = models.CharField(max_length=300, verbose_name="收货地址")
    
    # 价格信息
    total_amount = models.DecimalField(max_digits=10, decimal_places=2, verbose_name="订单总金额")
    discount_amount = models.DecimalField(max_digits=10, decimal_places=2, default=0, verbose_name="优惠金额")
    shipping_fee = models.DecimalField(max_digits=10, decimal_places=2, default=0, verbose_name="运费")
    actual_amount = models.DecimalField(max_digits=10, decimal_places=2, verbose_name="实付金额")
    
    # 订单信息
    remark = models.TextField(blank=True, null=True, verbose_name="订单备注")
    delivery_time = models.CharField(max_length=100, blank=True, null=True, verbose_name="期望送达时间")
    
    # 支付信息
    payment_method = models.CharField(max_length=20, blank=True, null=True, verbose_name="支付方式")
    payment_time = models.DateTimeField(blank=True, null=True, verbose_name="支付时间")
    transaction_id = models.CharField(max_length=100, blank=True, null=True, verbose_name="交易号")
    
    # 物流信息
    shipping_company = models.CharField(max_length=50, blank=True, null=True, verbose_name="物流公司")
    tracking_number = models.CharField(max_length=100, blank=True, null=True, verbose_name="物流单号")
    shipped_time = models.DateTimeField(blank=True, null=True, verbose_name="发货时间")
    delivered_time = models.DateTimeField(blank=True, null=True, verbose_name="送达时间")
    
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    updated_at = models.DateTimeField(auto_now=True, verbose_name="更新时间")

    class Meta:
        db_table = 'order'
        verbose_name = '订单'
        verbose_name_plural = '订单'
        ordering = ['-created_at']

    def __str__(self):
        return f"订单 {self.order_no}"

    @property
    def item_count(self):
        """订单商品数量"""
        return self.items.aggregate(
            total=models.Sum('quantity')
        )['total'] or 0


class OrderItem(models.Model):
    """订单商品"""
    order = models.ForeignKey(Order, related_name='items', on_delete=models.CASCADE, verbose_name="订单")
    flower = models.ForeignKey(Flower, on_delete=models.CASCADE, verbose_name="鲜花")
    flower_spec = models.ForeignKey(FlowerSpec, on_delete=models.CASCADE, null=True, blank=True, verbose_name="鲜花规格")
    
    # 商品信息快照
    flower_name = models.CharField(max_length=200, verbose_name="鲜花名称")
    flower_image = models.URLField(blank=True, null=True, verbose_name="鲜花图片")
    spec_name = models.CharField(max_length=100, blank=True, null=True, verbose_name="规格名称")
    
    # 价格数量
    unit_price = models.DecimalField(max_digits=10, decimal_places=2, verbose_name="单价")
    quantity = models.IntegerField(verbose_name="数量")
    total_price = models.DecimalField(max_digits=10, decimal_places=2, verbose_name="小计")
    
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")

    class Meta:
        db_table = 'order_item'
        verbose_name = '订单商品'
        verbose_name_plural = '订单商品'

    def __str__(self):
        return f"{self.order.order_no} - {self.flower_name}"

    def save(self, *args, **kwargs):
        # 自动计算小计
        self.total_price = self.unit_price * self.quantity
        super().save(*args, **kwargs)


class Cart(models.Model):
    """购物车"""
    user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name="用户")
    flower = models.ForeignKey(Flower, on_delete=models.CASCADE, verbose_name="鲜花")
    flower_spec = models.ForeignKey(FlowerSpec, on_delete=models.CASCADE, null=True, blank=True, verbose_name="鲜花规格")
    quantity = models.IntegerField(default=1, verbose_name="数量")
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    updated_at = models.DateTimeField(auto_now=True, verbose_name="更新时间")

    class Meta:
        db_table = 'cart'
        verbose_name = '购物车'
        verbose_name_plural = '购物车'
        unique_together = ['user', 'flower', 'flower_spec']
        ordering = ['-created_at']

    def __str__(self):
        return f"{self.user.nickname} - {self.flower.name}"

    @property
    def total_price(self):
        """计算总价"""
        if self.flower_spec:
            return self.flower_spec.price * self.quantity
        return self.flower.price * self.quantity


class OrderLog(models.Model):
    """订单日志"""
    order = models.ForeignKey(Order, related_name='logs', on_delete=models.CASCADE, verbose_name="订单")
    action = models.CharField(max_length=50, verbose_name="操作")
    description = models.TextField(verbose_name="描述")
    operator = models.CharField(max_length=50, blank=True, null=True, verbose_name="操作人")
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")

    class Meta:
        db_table = 'order_log'
        verbose_name = '订单日志'
        verbose_name_plural = '订单日志'
        ordering = ['-created_at']

    def __str__(self):
        return f"{self.order.order_no} - {self.action}"